﻿using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using Nutilities.Net;

namespace Auktionshuset___Server
{
    public class Broadcaster
    {
        private readonly List<Client> _clients;

        public Broadcaster(List<Client> clients)
        {
            _clients = clients;
        }

        public void Broadcast(byte message, IBinaryWriteable obj)
        {
            WriteTo(message, obj, _clients);
        }

        public void WriteTo(byte message, IBinaryWriteable obj, List<Client> clients)
        {
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(message);
                    obj.WriteTo(writer);
                    BroadcastTo(stream.ToArray(), clients);
                }
            }
        }

        public void UpdateTo(byte message, IBinaryUpdateable obj, List<Client> clients)
        {
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(message);
                    obj.UpdateTo(writer);
                    BroadcastTo(stream.ToArray(), clients);
                }
            }
        }

        public void BroadcastTo(byte[] bytes, List<Client> clients)
        {
            for (int i = clients.Count - 1; i >= 0; i--)
            {
                Client client = clients[i];
                if (client.Connected)
                {
                    try
                    {
                        client.Writer.Write(bytes);
                        client.Writer.Flush();
                    }
                    catch (SocketException)
                    {
                        if (client.Connected) continue;

                        clients.RemoveAt(i);
                        client.Stop();
                    }
                } else {
                    clients.RemoveAt(i);
                    client.Stop();
                }
            }
        }
    }
}
